package com.rk.cust.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final String ERROR_CODE_PARAM_VALID_FAIL= "mc.nbcb.cust.param.valid.001";

    private static final String ERROR_CODE_PARAM_VALID_FAIL2= "mc.nbcb.cust.param.valid.002";

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ConstraintViolationException.class)
    public ExceptionResponse validException(ConstraintViolationException e){
        log.warn("参数验证失败:{}",e.getLocalizedMessage());
        return new ExceptionResponse(ERROR_CODE_PARAM_VALID_FAIL,e.getLocalizedMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ExceptionResponse validException(MethodArgumentNotValidException e){
        String message =  String.join(", ",e.getBindingResult().getFieldErrors().stream()
                .map(error -> error.getField()+" "+error.getDefaultMessage()).collect(Collectors.toList()));
        log.warn("参数验证失败:{}",message);
        return new ExceptionResponse(ERROR_CODE_PARAM_VALID_FAIL2,message);
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(CustException.class)
    public ExceptionResponse validException(CustException e){
        log.warn("处理异常:{}",e.getErrorCode());
        return new ExceptionResponse(e.getErrorCode().getErrorCode(),e.getErrorCode().getErrorMsg());
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ExceptionResponse validException(Exception e){
        log.warn("系统出现内部错误",e);
        return new ExceptionResponse(ErrorCode.INTERNAL_SERVER_ERROR.getErrorCode(),ErrorCode.INTERNAL_SERVER_ERROR.getErrorMsg());
    }
}
